package com.mkz.core.zookeeper.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "zookeeper.curator")
public class ZookeeperConfig {
	private String connectString;
	private int sessionTimeoutMs;
	private int connectionTimeoutMs;
	private int retryTime;
	private int retryDistance;

	@Bean
	public CuratorFramework zkCurator() {
		// 创建重试策略
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(retryDistance, retryTime);
		// 创建zookeeper客户端
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
				.sessionTimeoutMs(sessionTimeoutMs).connectionTimeoutMs(connectionTimeoutMs).retryPolicy(retryPolicy)
				.build();

		client.start();
		log.info("Zookeeper初始化成功");
		return client;
	}
}